<?php

namespace Home\Controller;

class CashierController extends BaseMemberController {

    function _initialize() {
        parent::_initialize();
        $this->_user_id = session('visitor.user_id');
    }

    /*
     * * @api {get} /index.php?m=Home&c=Cashier&a=post_order 支付接口
     */

    function post_order() {
        $order_ids = I('request.order_ids');
        if (!$order_ids) {
            render('10001', '缺少参数');
        }
        $order_info = array(
            'order_amount' => 0,
            'order_sn' => '',
            'pd_amount' => 0,
            'money' => 0,
        );
        $order_ids_array = explode(',', $order_ids);
        if (empty($order_ids_array)) {
            render('19999', '输入参数错误');
        }
        $member_info = M('Member')->where('user_id=' . $this->_user_id)->find();
        $member_money = $member_info['money'];

        foreach ($order_ids_array as $order_id) {
            if (!$order_info0 = M('Order')->where('order_id=' . $order_id . ' AND buyer_id=' . $this->_user_id)->find()) {
                render('10500', '此订单不存在');
            }
            /* 订单有效性判断 */
            if ($order_info0['payment_code'] != 'cod' && $order_info0['status'] != ORDER_PENDING) {
                render('10518', '此订单不是代付款状态');
            }
            $order_info['order_amount'] = bcadd($order_info['order_amount'], $order_info0['order_amount'], 2);
            if (!$order_info['order_sn']) {
                $order_info['order_sn'] = $order_info0['order_sn'];
            } else {
                $order_info['order_sn'].=',' . $order_info0['order_sn'];
            }
            /* 使用余额支付 当用户选择部分预付款支付时 */
            if ($order_info0['pd_amount'] != '0.00') {
                if ($member_money >= $order_info0['order_amount']) {
                    $use_pd++;
                    $member_money = bcsub($member_money, $order_info0['order_amount'], 2);
                    //有足够的余额，直接进行支付
                    M('Order')->where('order_id=' . $order_id)->save(array('pd_amount' => $order_info0['order_amount']));
                } else {
                    //没有足够的余额，则把预付款支付设置为余额设置为最大值
                    M('Order')->where('order_id=' . $order_id)->save(array('pd_amount' => $member_money));
                    $order_info0['pd_amount'] = $member_money;
                    $member_money = 0;
                }
            }
            $order_info['pd_amount'] = bcadd($order_info['pd_amount'], $order_info0['pd_amount'], 2);
        }
        $order_info['money'] = bcsub($order_info['order_amount'], $order_info0['pd_amount'], 2);
        //得出订单具体支付金额 END


        $payment_code = I('request.payment_code');
        $payment_name = I('request.payment_name');
        if (!$payment_code || !$payment_name) {
            render('10525', '支付名称为空');
        }
        /* 保存支付方式 */
        $edit_data = array(
            'payment_name' => $payment_name,
            'payment_code' => $payment_code,
            'payment_id' => 0
        );

        M('Order')->where('order_id IN(' . implode(',', $order_ids_array) . ')')->save($edit_data);

        $order_info_array = array();
        $order_info_array['is_order_array'] = 1;
        $order_info_array['item'] = array();
        foreach ($order_ids_array as $order_id) {
            $order_info_array['item'][$order_id] = M('order')->where("order_id=" . $order_id . " AND buyer_id=" . $this->_user_id)->find();
        }

        $order_info_array['openid'] = I('request.openid');

        if ($payment_code == 'wxpay_app') {
            //调用微信支付
            import('Mall.Payment.Wxpay.WxPayment', '', '.php');
            $payment = new \WxPayment();
            $payment->get_payform($order_info_array);
        } elseif ($payment_code == 'alipay_app') {
            //调用支付宝
            import('Mall.Payment.Alipay.AliPayment', '', '.php');
            $payment = new \AliPayment();
            $payment->get_payform($order_info_array);
        } elseif ($payment_code == 'jspay_app') {
            //调用微信支付
            import('Mall.Payment.Wxpay.WxPayment', '', '.php');
            $payment = new \WxPayment();
            $payment->get_payform2($order_info_array);
        } else {
            render('19999', '未选择支付');
        }
    }

    /**
     * @api {get} /index.php?m=Home&c=Cashier&a=index 获取订单支付信息
     */
    function index() {
        $order_ids = I('request.order_ids');
        if (!$order_ids) {
            render('10001', '缺少参数');
        }
        $order_info = array(
            'order_amount' => 0,
            'order_sn' => '',
            'pd_amount' => 0,
            'money' => 0,
        );
        $order_ids = explode(',', $order_ids);
        $member_info = M('Member')->where('user_id=' . $this->_user_id)->find();
        $payments = array();
        $member_money = $member_info['money'];


        foreach ($order_ids as $order_id) {
            if (!$order_info0 = M('Order')->where('order_id=' . $order_id)->find()) {
                render('10500', '此订单不存在');
            }
            /* 订单有效性判断 */
            if ($order_info0['payment_code'] != 'cod' && $order_info0['status'] != ORDER_PENDING) {
                render('10518', '此订单不是代付款状态');
            }
            $order_info['order_amount'] = bcadd($order_info['order_amount'], $order_info0['order_amount'], 2);
            if (!$order_info['order_sn']) {
                $order_info['order_sn'] = $order_info0['order_sn'];
            } else {
                $order_info['order_sn'].=',' . $order_info0['order_sn'];
            }
            /* 使用余额支付 当用户选择部分预付款支付时 */

            if ($order_info0['pd_amount'] != '0.00') {
                if ($member_money >= $order_info0['order_amount']) {
                    $use_pd++;
                    $member_money = bcsub($member_money, $order_info0['order_amount'], 2);
                    //有足够的余额，直接进行支付
                    M('Order')->where('order_id=' . $order_id)->save(array('pd_amount' => $order_info0['order_amount']));
                } else {
                    //没有足够的余额，则把预付款支付设置为余额设置为最大值
                    M('Order')->where('order_id=' . $order_id)->save(array('pd_amount' => $member_money));
                    $order_info0['pd_amount'] = $member_money;
                    $member_money = 0;
                }
            }
            $order_info['pd_amount'] = bcadd($order_info['pd_amount'], $order_info0['pd_amount'], 2);
        }
        $order_info['money'] = bcsub($order_info['order_amount'], $order_info0['pd_amount'], 2);
        if (count($order_ids) == 1) {//如果只有一个订单，则显示店铺开启的支付方式
            $payments = D('Payment')->get_enabled($order_info0['seller_id']);
        }

        /* 找出配送方式，判断是否可以使用货到付款 */
        $consignee_info = M('OrderExtm')->where('order_id=' . $order_id)->find();
        if (!empty($consignee_info)) {
            /* 需要配送方式 */
            $shipping_info = M('Shipping')->where('shipping_id=' . $consignee_info['shipping_id'])->find();
            $cod_regions = unserialize($shipping_info['cod_regions']);
            $cod_usable = true; //默认可用
            if (is_array($cod_regions) && !empty($cod_regions)) {
                /* 取得支持货到付款地区的所有下级地区 */
                $all_regions = array();
                foreach ($cod_regions as $region_id => $region_name) {
                    $all_regions = array_merge($all_regions, D('Region')->get_descendant($region_id));
                }

                /* 查看订单中指定的地区是否在可货到付款的地区列表中，如果不在，则不显示货到付款的付款方式 */
                if (!in_array($consignee_info['region_id'], $all_regions)) {
                    $cod_usable = false;
                }
            } else {
                $cod_usable = false;
            }
            if (!$cod_usable) {
                /* 从列表中去除货到付款的方式 */
                foreach ($payments as $_id => $_info) {
                    if ($_info['payment_code'] == 'cod') {
                        /* 如果安装并启用了货到付款，则将其从可选列表中去除 */
                        unset($payments[$_id]);
                    }
                }
            }
        }

        if (!IS_POST) {
            render('10000', '', array('order_info' => $order_info, 'member_info' => $member_info, 'payments' => $payments));
        } else {
            if (!isset($_POST['online'])) {
                $payment_id = intval(I('post.payment_id'));
                if (count($order_ids) > 1 && $payment_id > 0) {
                    render('10519', '多个订单不能使用线下支付方式');
                }
                if ($payment_id == 0) {//使用余额支付
                    $zf_pass = I('post.zf_pass');
                    if (!$zf_pass) {
                        render('10520', '支付密码为空');
                    }
                    if (empty($member_info['zf_pass'])) {
                        M('Member')->where("user_id=" . $this->_user_id)->save(array('zf_pass' => md5('123456')));
                        $member_info['zf_pass'] = md5('123456');
                    }
                    if ($member_info['zf_pass'] != md5($zf_pass)) {
                        render('10521', '支付密码错误');
                    }
                    //检测余额是否足够
                    if ($member_info['money'] < $order_info['order_amount']) {//此时为所有订单总金额
                        render('10522', '用户余额不足');
                    }
                    foreach ($order_ids as $order_id) {
                        $order_info = M('Order')->where("order_id=" . $order_id . " AND buyer_id=" . $this->_user_id)->find();
                        //读取卖家SQL
                        $seller_row = M('Member')->where("user_id=" . $order_info['seller_id'])->find();


                        $seller_id = $seller_row['user_id']; #卖家ID 
                        $seller_name = $seller_row['user_name']; #卖家用户名
                        //买家添加日志
                        $time = time();
                        $buyer_log_text = '购买商品，店主 ' . $seller_name;
                        $buyer_add_array = array(
                            'user_id' => $this->_user_id,
                            'user_name' => $member_info['user_name'],
                            'order_id' => $order_id,
                            'order_sn' => $order_info['order_sn'],
                            'add_time' => $time,
                            'type' => ACCOUNT_TYPE_BUY,
                            'money_flow' => 'outlay',
                            'money' => $order_info['order_amount'], //单个订单金额
                            'log_text' => $buyer_log_text,
                            'states' => 20,
                        );
                        D('Accountlog')->change_money($buyer_add_array);
                        //卖家添加日志
                        $seller_log_text = '出售商品，买家 ' . $member_info['user_name'];
                        $seller_add_array = array(
                            'user_id' => $seller_id,
                            'user_name' => $seller_name,
                            'order_id' => $order_id,
                            'order_sn' => $order_info['order_sn'],
                            'add_time' => $time,
                            'type' => ACCOUNT_TYPE_SELLER,
                            'money_flow' => 'income',
                            'money' => $order_info['order_amount'],
                            'log_text' => $seller_log_text,
                            'states' => 20,
                        );
                        D('Accountlog')->change_money($seller_add_array);
                        //改变定单为 已支付等待卖家确认  status10改为20
                        $payment_code = "zjgl";
                        //更新定单状态
                        $order_edit_array = array(
                            'payment_name' => '预付款',
                            'payment_code' => $payment_code,
                            'pay_time' => $time,
                            'status' => ORDER_ACCEPTED, //20就是 待发货了
                        );
                        M('Order')->where('order_id=' . $order_id)->save($order_edit_array);
                    }
                    render('10000', '支付成功');
                } else {//线下支付
                    $pay_message = I('post.pay_message');
                    if (!$pay_message) {
                        render('10523', '没有填写付款信息');
                    }
                    $can_pay = false;
                    $the_payment = array();
                    foreach ($payments as $payment) {
                        if ($payment['payment_id'] == $payment_id) {
                            $can_pay = true;
                            $the_payment = $payment;
                        }
                    }
                    if (!$can_pay) {
                        render('10524', '卖家没启用该支付方式');
                    }
                    /* 保存支付方式 */
                    $edit_data = array(
                        'payment_id' => $payment['payment_id'],
                        'payment_code' => $payment['payment_code'],
                        'payment_name' => $payment['payment_name'],
                        'pay_message' => $pay_message
                    );
                    /* 如果是货到付款，则改变订单状态 */
                    if ($payment['payment_code'] == 'cod') {
                        $edit_data['status'] = ORDER_SUBMITTED;
                    }

                    M('Order')->where('order_id=' . $order_id)->save($edit_data);

                    render('10000', '支付信息提交完成');
                }
            } else {//使用线上支付
                $payment_name = I('post.payname');
                if (!$payment_name) {
                    render('10525', '支付名称为空');
                }
                /* 保存支付方式 */
                $edit_data = array(
                    'payment_name' => $payment_name,
                );

                M('Order')->where('order_id IN(' . implode(',', $order_ids) . ')')->save($edit_data);

                //生成资金记录
                $account_log = array(
                    'user_id' => $order_info0['buyer_id'],
                    'user_name' => $order_info0['buyer_name'],
                    'add_time' => time(),
                    'type' => ACCOUNT_TYPE_CZ,
                    'money_flow' => 'income',
                    'money' => $order_info['money'],
                    'log_text' => $order_info0['buyer_name'] . "充值" . $order_info['money'] . "元(" . $payment_name . ")",
                );
                if (count($order_ids) > 1) {
                    $order_sn = D('Order')->_gen_order_sn();
                    $account_log['order_sn'] = $order_sn;
                    $account_log['orders_group'] = implode(',', $order_ids);
                } else {
                    $account_log['order_id'] = $order_info0['order_id'];
                    $account_log['order_sn'] = $order_info0['order_sn'];
                }
                M('AccountLog')->add($account_log);
                render('10000', '资金记录生成成功', $account_log['order_sn']);
            }
        }
    }

    
    /**
     * @api {get} /index.php?m=Home&c=Cashier&a=ali_test 支付宝支付测试
     */
    function ali_test() {
        $order_info = array(
            'buyer_id' => session('visitor.user_id'),
            'buyer_name' => session('visitor.user_name'),
            'order_amount' => 0.01,
            'order_sn' => date('YmdHis', time()) . rand(1000, 9999),
        );
        import('Mall.Payment.Alipay.AliPayment', '', '.php');
        $payment = new \AliPayment();
        $payment->get_payform($order_info);
    }
    

    /**
     * @api {get} /index.php?m=Home&c=Cashier&a=wx_test 微信支付测试
     */
    function wx_test() {
        $order_info = array(
            'buyer_id' => session('visitor.user_id'),
            'buyer_name' => session('visitor.user_name'),
            'order_amount' => 0.01,
            'order_sn' => date('YmdHis', time()) . rand(1000, 9999),
        );
        import('Mall.Payment.Wxpay.WxPayment', '', '.php');
        $payment = new \WxPayment();
        $payment->get_payform($order_info);
    }

}
